import request from './request';
import { useUserStore } from '@/stores/user';
import { UserInterface } from '@/typings/user';
import { NEED_LOGIN_TYPES } from '@/constants/base';

request.setConfig({
  baseUrl: import.meta.env.VITE_APP_BASE_API,
  debug: true
});

// 请求拦截
request.interceptor.request = (config) => {
  const userStore = useUserStore();
  config.header.Accept = 'application/json';

  // 给header添加全局请求参数token
  if (!config.header.token) {
    config.header.Authorization = 'Bearer ' + userStore.token;
  }
  // 添加一个自定义的参数，默认异常请求都弹出一个toast提示
  if (config.toastError === undefined) {
    config.toastError = true;
  }
  return config;
};

// 响应拦截
request.interceptor.response = (res) => {
  if (res.code === 0) {
    res.success = true;
  } else if (NEED_LOGIN_TYPES.includes(res.code)) {
    toLogin();
  }
  return res;
};

// 全局的错误异常处理
request.interceptor.fail = (res, config) => {
  let ret;
  let msg = '';
  if (res.statusCode === 200) {
    // 业务错误
    msg = (res.data as AnyObject).msg;
    ret = res;
  } else if (res.statusCode === 401) {
    // token失效，需要重新登录
    uni.navigateTo({
      url: '/pages/loign/login'
    });
  } else if (res.statusCode === 500) {
    // 其它错误
    msg = (res.data as AnyObject).error.message;
  } else if (res.statusCode > 0) {
    // HTTP错误
    msg = '服务器异常[' + res.statusCode + ']';
  } else {
    msg = res.errMsg;
  }

  if (config.toastError && msg) {
    uni.showToast({
      title: msg,
      duration: 2000,
      icon: 'none'
    });
  }

  console.log(ret, 12321312321312);

  return ret || msg;
};

function toLogin() {
  const { login, getUserInfo, setUser } = useUserStore();
  login().then((res) => {
    getUserInfo(res.code).then((res) => {
      console.log('登录成功');
      setUser(<UserInterface>res);
    });
  });
}

export default request;
